package com.apimanage.user.service.impl;


import com.apimanage.common.dto.AuthDTO;
import com.apimanage.common.dto.UserDTO;
import com.apimanage.user.entity.User;
import com.apimanage.user.mapper.UserMapper;
import com.apimanage.common.service.UserCenterService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户服务实现类
 *
 * @author API管理平台
 */
@DubboService
public class UserServiceImpl implements UserCenterService {

    @Autowired
    private UserMapper userMapper;

    /**
     * User转UserDTO
     */
    private UserDTO convertToDTO(User user) {
        if (user == null) {
            return null;
        }
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        // 设置默认角色为USER
        List<String> roles = new ArrayList<>();
        roles.add("USER");
        userDTO.setRoles(roles);
        return userDTO;
    }

    /**
     * UserDTO转User
     */
    private User convertToEntity(UserDTO userDTO) {
        if (userDTO == null) {
            return null;
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        return user;
    }

    @Override
    public UserDTO getUserById(Long id) {
        User user = userMapper.selectById(id);
        return convertToDTO(user);
    }

    @Override
    public UserDTO getUserByUsername(String username) {
        User user = userMapper.findByUsername(username);
        return convertToDTO(user);
    }

    @Override
    @Transactional
    public boolean updateUser(UserDTO userDTO) {
        User user = convertToEntity(userDTO);
        // 设置更新时间
        user.setUpdateTime(new Date());

        // 不更新密码
        user.setPassword(null);

        return userMapper.updateById(user) > 0;
    }

    @Override
    @Transactional
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        // 获取用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 注意：密码校验逻辑已移至auth-center模块
        // 简单验证保持功能连续性
        if (!oldPassword.equals(user.getPassword())) {
            throw new RuntimeException("旧密码不正确");
        }

        // 更新密码
        User updateUser = new User();
        updateUser.setId(userId);
        // 注意：密码加密逻辑已移至auth-center模块，此处保持原始密码
        updateUser.setPassword(newPassword);
        updateUser.setUpdateTime(new Date());

        return userMapper.updateById(updateUser) > 0;
    }

    @Override
    @Transactional
    public boolean resetPassword(Long userId, String newPassword) {
        // 获取用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 更新密码
        User updateUser = new User();
        updateUser.setId(userId);
        // 注意：密码加密逻辑已移至auth-center模块，此处保持原始密码
        updateUser.setPassword(newPassword);
        updateUser.setUpdateTime(new Date());

        return userMapper.updateById(updateUser) > 0;
    }

    @Override
    @Transactional
    public boolean updateUserStatus(Long userId, Integer status) {
        // 获取用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 更新状态
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setStatus(status);
        updateUser.setUpdateTime(new Date());

        return userMapper.updateById(updateUser) > 0;
    }

    @Override
    public List<UserDTO> getUserList(Integer page, Integer pageSize) {
        // 计算偏移量
        int offset = (page - 1) * pageSize;
        List<User> users = userMapper.selectList(null);
        List<UserDTO> userDTOs = new ArrayList<>();
        for (User user : users) {
            userDTOs.add(convertToDTO(user));
        }
        return userDTOs;
    }

    @Override
    public int countUsers() {
        // 修复类型转换问题：将Long转换为Integer
        Long count = userMapper.selectCount(null);
        return count.intValue();
    }

    @Override
    public boolean registerWithAuthDTO(AuthDTO authDTO) {
        // 检查用户名是否已存在
        User existingUser = userMapper.findByUsername(authDTO.getUsername());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 创建用户实体
        User user = new User();
        user.setUsername(authDTO.getUsername());
        // 直接使用auth-center已经加密好的密码
        user.setPassword(authDTO.getPassword());
        user.setEmail(authDTO.getEmail());
        user.setPhone(authDTO.getPhone());
        user.setRole(authDTO.getRole()); // 设置默认角色为普通用户
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setStatus(1); // 默认启用状态
        
        // 保存用户
        userMapper.insert(user);
        
        return true;
    }


}